// ignore_for_file: library_private_types_in_public_api, use_build_context_synchronously

import 'dart:convert';
import 'dart:math';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/key_management_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flutter/material.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class AddKeyPage extends StatefulWidget {
  const AddKeyPage({super.key});

  @override
  _AddKeyPageState createState() => _AddKeyPageState();
}

class _AddKeyPageState extends State<AddKeyPage> {
  final _formKey = GlobalKey<FormState>();
  String? _newKeyName;
  String? _newKeyValue;
  final TextEditingController _secretKeyController = TextEditingController();

  @override
  void dispose() {
    _secretKeyController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Add Key'.t(context)),
        centerTitle: true,
        backgroundColor: themeProvider.mainColor,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(labelText: 'New Name'.t(context)),
                onChanged: (value) => _newKeyName = value,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter a name'.t(context);
                  }
                  return null;
                },
              ),
              const SizedBox(
                height: 15,
              ),
              TextFormField(
                decoration:
                    InputDecoration(labelText: 'New Secret Key'.t(context)),
                controller: _secretKeyController,
                onChanged: (value) => _newKeyValue = value,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter a key'.t(context);
                  }
                  return null;
                },
              ),
              const SizedBox(
                height: 15,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        if (_newKeyValue!.length != 16) {
                          Fluttertoast.showToast(
                              msg: 'The key must contain 16 characters.'
                                  .t(context));
                          return;
                        }
                        if (!RegExp(r'^[a-zA-Z0-9]{16}$')
                            .hasMatch(_newKeyValue ?? '')) {
                          Fluttertoast.showToast(
                              msg: 'The key must be letters or numbers.'
                                  .t(context));
                          return;
                        }
                        _addKey(SecretKeyModel(
                          name: _newKeyName!,
                          key: _newKeyValue!,
                        ));
                      }
                    },
                    child: Text('Add Key'.t(context)),
                  ),
                  const SizedBox(width: 20),
                  ElevatedButton(
                    onPressed: () {
                      final random = Random.secure();
                      final bytes =
                          List<int>.generate(12, (_) => random.nextInt(128));
                      _newKeyValue = base64UrlEncode(bytes);
                      _secretKeyController.text = _newKeyValue!; // 使用 Base64 编码
                    },
                    child: Text('Random generation'.t(context)),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _addKey(SecretKeyModel model) async {
    const url = '/add_key';
    String token = SpUtil.getString('token') ?? '';

    var params = {
      'key': model.key,
      'name': model.name,
    };
    var response = await DioHttp.of(context).post(url, params, token);
    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      Navigator.pop(context);
    }
  }
}
